import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  },
  {
    path: '/chart',
    name: 'chart',
    component: () => import(/* webpackChunkName: "chart" */'../views/chart/index.vue')
  },
  {
    path: '/demo',
    name: 'demo',
    component: () => import(/* webpackChunkName: "demo" */'../views/demo/index.vue')
  },
  // 登录页
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ '../views/login/index.vue')
  },
  // 首页
  {
    path: '/home',
    name: 'home',
    component: () => import(/* webpackChunkName: 'home' */ '../views/home.vue'),
    children: [
      {
        path: '/searchComponent',
        name: 'searchComponent',
        component: () => import(/* webpackChunkName: "searchComponent" */'../views/searchComponent.vue'),
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
});

/**
 * 路由拦截
 * 功能：权限校验
 * */
router.beforeEach((to, from, next) => {
  // 路由跳转时，判断session中是否有用户信息，key为token
  // 有则继续跳转，没有则重定向到登录
  if (sessionStorage.getItem('token')) {
    next()
  } else {
    // 如果没有token，那么跳转到登录，但是走push方法又会再次进来这个方法，从而无线循环，所有要加判断跳转的地址是不是登录
    if (to.path === '/login') {
      next()
    } else {
      router.push('/login');
    }
  }
});

export default router
